#include "mg_string.h"


//将16进制数转化为字符串
void HexToStr(uint8_t *pbDest, char *pbSrc, int nLen)
{
	char    ddl, ddh;
	int i;

	for (i = 0; i<nLen; i++)
	{
		ddh = 48 + pbSrc[i] / 16;
		ddl = 48 + pbSrc[i] % 16;
		if (ddh > 57) ddh = ddh + 7;
		if (ddl > 57) ddl = ddl + 7;
		pbDest[i * 2] = ddh;
		pbDest[i * 2 + 1] = ddl;
	}

	pbDest[nLen * 2] = '\0';
}
//判断单个UTF8字符长度
int Get_UTF8_Byte_Size(const unsigned char Input)
{
	unsigned char c = Input;
	// 0xxxxxxx 返回0
	// 10xxxxxx 不存在
	// 110xxxxx 返回2
	// 1110xxxx 返回3
	// 11110xxx 返回4
	// 111110xx 返回5
	// 1111110x 返回6
	if (c< 0x80) return 1;
	if (c >= 0x80 && c<0xC0) return -1;
	if (c >= 0xC0 && c<0xE0) return 2;
	if (c >= 0xE0 && c<0xF0) return 3;
	if (c >= 0xF0 && c<0xF8) return 4;
	if (c >= 0xF8 && c<0xFC) return 5;
	if (c >= 0xFC) return 6;
	return -1;
}
//判断UTF字符串字符个数
uint8_t Get_UTF8_Str_Size(unsigned char *pInput, uint8_t InputLen)
{
	uint8_t TempLen, ByteLen = 0;
	uint8_t HaveChinese = 0;
	int ByteSize;
	TempLen = InputLen;
	while (TempLen>0 && pInput[InputLen - TempLen] != 0)
	{
		ByteSize = Get_UTF8_Byte_Size(pInput[InputLen - TempLen]);
		if (ByteSize > 0)
		{
			if (ByteSize == 3)HaveChinese = 1;
			ByteLen++;
		}
		else
		{
			break;
		}
		TempLen -= ByteSize;
	}
	return ByteLen;
}
//返回合理的文字换行格式(两行)
UTF8_TWO_LINE Get_UTF8_Two_Line(unsigned char *pInput, uint8_t InputLen)
{
	UTF8_TWO_LINE DeviceName;
	uint8_t i;
	int ByteSize = 0;
	//换行
	uint8_t TempLen = InputLen, ByteLen = 0;	//字符转义后长度
	uint8_t HaveChinese = 0;		//是否有中文
	while (TempLen>0 && pInput[InputLen - TempLen] != 0)
	{
		ByteSize = Get_UTF8_Byte_Size(pInput[InputLen - TempLen]);
		if (ByteSize > 0)
		{
			if (ByteSize == 3)HaveChinese = 1;
			ByteLen++;
		}
		else
			break;
		TempLen -= ByteSize;
	}

	//赋值名称
	memset(DeviceName.DeviceName1, 0, sizeof(DeviceName.DeviceName1));
	memset(DeviceName.DeviceName2, 0, sizeof(DeviceName.DeviceName2));
	if (HaveChinese)//存在中文
	{
		if (ByteLen <= 3)
		{
			memcpy(DeviceName.DeviceName1, pInput, InputLen);
		}
		else
		{
			ByteSize = 0;
			for (i = 0; i < ByteLen / 2; i++)
				ByteSize += Get_UTF8_Byte_Size(pInput[ByteSize]);
			memcpy(DeviceName.DeviceName1, pInput, ByteSize);
			memcpy(DeviceName.DeviceName2, &pInput[ByteSize], InputLen - ByteSize);
		}
	}
	else//只有英文或符号
	{
		uint8_t HavePause = 0;
		for (i = 0; i < ByteLen; i++)
		{
			if (pInput[i] == ' ')//存在空格
			{
				if (i < 10)
				{
					memcpy(DeviceName.DeviceName1, pInput, i);
					memcpy(DeviceName.DeviceName2, &pInput[i + 1], InputLen - i - 1);
				}
				else
				{
					memcpy(DeviceName.DeviceName1, pInput, 10);
					memcpy(DeviceName.DeviceName2, &pInput[10], InputLen - 10);
				}
				HavePause = 1;
				break;
			}
		}
		if (!HavePause)//没有空格
		{
			if (ByteLen > 10)
			{
				memcpy(DeviceName.DeviceName1, pInput, 10);
				memcpy(DeviceName.DeviceName2, &pInput[10], InputLen - 10);
			}
			else
			{
				memcpy(DeviceName.DeviceName1, pInput, ByteLen);
			}
		}
	}

	return DeviceName;
}